const electron = window.require('electron');
export  function delay(timeout = 10000): Promise<void> {
    return new Promise(async (resolve, reject) => {
        setTimeout(() => {
           resolve(); 
        }, timeout);
    })
}

export async function setKeyboardDelay(ms: number): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "setKeyboardDelay", { ms: ms });
}

export async function setMouseDelay(delay: number): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "setMouseDelay", { delay: delay });
}


export async function keyTap(key: string, modifier?: string | string[]): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "keyTap", { key: key, modifier: modifier });
}

export async function keyToggle(key: string, down: string, modifier?: string | string[]): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "keyTap", { key: key, modifier: modifier });
}

export async function typeString(string: string): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "typeString", { string: string });
}


export async function moveMouse(x: number, y: number) {
    return await electron.ipcRenderer.invoke("robotjs", "moveMouse", { x: x, y: y });
}

export async function mouseClick(button: string = "left", double: boolean = false): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "mouseClick", { button: button, double: double });
}

export async function mouseToggle(down?: string, button?: string): Promise<void> {
    return await electron.ipcRenderer.invoke("robotjs", "mouseToggle", { down: down, button: button });
}

export async function getScreenSize(): Promise<{ width: number, height: number }> {
    return await electron.ipcRenderer.invoke("robotjs", "getScreenSize");
}

export async function getMousePos(): Promise<{ x: number, y: number }> {
    return await electron.ipcRenderer.invoke("robotjs", "getMousePos");
}

export async function getPixelColor(x: number, y: number): Promise<string> {
    return `#${await electron.ipcRenderer.invoke("robotjs", "getPixelColor", { x: x, y: y })}`;
}

export async function getPixelColorRGB(x: number, y: number): Promise<{ r: number, g: number, b: number }> {
    const colorStr = await getPixelColor(x, y)
    console.log("getPixelColorRGB", colorStr);

    return hexToRgb(`${colorStr}`)
}

export async function getMousePosColor(): Promise<string> {
    const pos = await getMousePos()
    return await getPixelColor(pos.x, pos.y);
}

export async function compress(path: string): Promise<void> {
    return await electron.ipcRenderer.invoke("tinypng", "compress", { path: path });
}

export function hexToRgb(val: string): { r: number, g: number, b: number } {   //HEX十六进制颜色值转换为RGB(A)颜色值
    var r, g, b;
    if ((/^#/g).test(val)) {
        r = val.slice(1, 3);
        g = val.slice(3, 5);
        b = val.slice(5, 7);
        return { r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16) };
    } else {
        return { r: 0, g: 0, b: 0 };
    }
}

export function rgbToCommonColor(color: { r: number, g: number, b: number }): ECommonColor {
    const bp = 50//R、G、B低于此值就算黑色
    const wp = 230//R、G、B高于此值就算白色
    const gp = 15//R、G、B差距小于此值就算灰色
    const r = color.r;
    const g = color.g;
    const b = color.b;
    let result: ECommonColor = ECommonColor.Black
    //判断上面三个参数
    if (r < bp && b < bp && b < bp) {
        result = ECommonColor.Black
    } else if (r > wp && g > wp && b > wp) {
        result = ECommonColor.White
    } else if (Math.abs(r - g) < gp && Math.abs(r - b) < gp && Math.abs(g - b) < gp) {
        result = ECommonColor.Gray
    } else if (r == b && b == g) {
        //如果R、G、B相等（非彩色）
        if (r < bp) {
            result = ECommonColor.Black
        } else if (r > wp) {
            result = ECommonColor.White

        } else {
            result = ECommonColor.Gray
        }
    } else if (r == b) {//如果是单色，看看亮度 	
        if (r < g) {//绿色比较高，就是绿色 
            result = ECommonColor.Green
        } else {
            result = ECommonColor.Purple
        }
    } else if (r == g) {//如果是单色，看看亮度 	
        if (r < b) {//蓝色比较高，就是蓝色
            result = ECommonColor.Blue
        } else {
            result = ECommonColor.Yellow
        }
    } else if (g == b) {//如果是单色，看看亮度 	
        if (g < r) {//红色比较高，就是红色
            result = ECommonColor.Red
        } else {
            result = ECommonColor.Cyan
        }
    } else {
        //下面是混合色 	
        if (r > g && r > b) {
            if (b - g > (r - g) / 2) {
                result = ECommonColor.Purple
            } else if (g - b > (r - b) / 3) {
                if (r / g < 1.25) {
                    result = ECommonColor.Yellow
                } else {
                    result = ECommonColor.Orange
                }
            } else {
                result = ECommonColor.Red
            }
        } else if (g > r && g > b) {
            if (r - b > (g - b) / 2) {
                result = ECommonColor.Yellow
            } else if (b - r > (g - r)) {
                result = ECommonColor.Cyan
            } else {
                result = ECommonColor.Green
            }
        } else if (b > r && b > g) {
            if (r - g > (b - g) / 30) {
                result = ECommonColor.Purple
            } else if (g - r > (b - r) / 1.5) {
                result = ECommonColor.Cyan
            } else {
                result = ECommonColor.Blue
            }
        }
    }

    return result
}

export enum ECommonColor {
    Red,
    Orange,
    Yellow,
    Green,
    Cyan,
    Blue,
    Purple,
    Black,
    White,
    Gray
}

export function getCommonColorName(color: ECommonColor): string {
    switch (color) {
        case ECommonColor.Red:
            return "红"
        case ECommonColor.Orange:
            return "橙"
        case ECommonColor.Yellow:
            return "黄"
        case ECommonColor.Green:
            return "绿"
        case ECommonColor.Cyan:
            return "青"
        case ECommonColor.Blue:
            return "蓝"
        case ECommonColor.Purple:
            return "紫"
        case ECommonColor.Black:
            return "黑"
        case ECommonColor.White:
            return "白"
        case ECommonColor.Gray:
            return "灰"


        default:
            return "无色"
    }
}


export class ViewColorFeature {
    constructor(
        public x: number,
        public y: number,
        public commonColor: ECommonColor
    ) { }
}



export class View {
    constructor(
        public name: string,
        public features: ViewColorFeature[]
    ) { }
    async isCurrentView() {
        for (let index = 0; index < this.features.length; index++) {
            const element = this.features[index];
            const color = rgbToCommonColor(
                await getPixelColorRGB(element.x, element.y)
            )
            if (color !== element.commonColor) {
                return false
            }
        }
        return true
    }

    waitToActive(intervel = 200, timeout = 15000): Promise<boolean> {
        return new Promise(async (resolve, reject) => {
            if (await this.isCurrentView()) {
                resolve(true)
            } else {
                const startTime = Date.now();
                const timer = setInterval(async () => {
                    console.log("timer");
                    
                    if (await this.isCurrentView()) {
                        resolve(true)
                        clearInterval(timer)
                    } else if (Date.now() - startTime >= timeout) {
                        resolve(false)
                        clearInterval(timer)
                    }
                }, intervel)
            }
        })
    }
}

export default {
    delay,
    setKeyboardDelay,
    keyTap,
    keyToggle,
    typeString,
    setMouseDelay,
    moveMouse,
    mouseClick,
    mouseToggle,
    getScreenSize,
    getMousePos,
    getPixelColor,
    getPixelColorRGB,
    getMousePosColor,
    rgbToCommonColor,
    getCommonColorName,
    hexToRgb,
    compress

}